package com.hopital5.zhangyz.vo.request;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

import java.util.Map;
import java.util.NoSuchElementException;

/**
 * Created by zhangyz on 16-4-25.
 */
public abstract class BaseRequest {
    private String currentUserId;
    private Map<String, String> sort;
    private Integer current = 1;
    private Integer size = 20;

    public Specification<?> toSpecification() {
        return null;
    }

    public Pageable getPageable() {
        {
            if (this.sort == null || this.sort.isEmpty()) {
                return new PageRequest(this.getCurrent(), this.getSize());
            }
            try {
                Sort sort = this.sort.entrySet().stream()
                        .map((entry) -> new Sort("DESC".equalsIgnoreCase(entry.getValue())
                                ? Sort.Direction.DESC
                                : Sort.Direction.ASC,
                                entry.getKey()))
                        .reduce(Sort::and)
                        .get();
                return new PageRequest(this.getCurrent(), this.getSize(), sort);
            } catch (NoSuchElementException ex) {
                return new PageRequest(this.getCurrent(), this.getSize());
            }
        }

    }

    public String getCurrentUserId() {
        return currentUserId;
    }

    public void setCurrentUserId(String currentUserId) {
        this.currentUserId = currentUserId;
    }

    public Map<String, String> getSort() {
        return sort;
    }

    public void setSort(Map<String, String> sort) {
        this.sort = sort;
    }

    public Integer getCurrent() {
        return current <= 0 ? 0 : current - 1;
    }

    public void setCurrent(Integer current) {
        this.current = current;
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }

}
